package com.example.hetong_system.service;

import com.alipay.easysdk.factory.Factory;
import com.example.hetong_system.model.Contract;
import com.example.hetong_system.model.PaymentPlan;
import com.example.hetong_system.repository.ContractRepository;
import com.example.hetong_system.repository.PaymentPlanRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;

@Service
public class PaymentService {

    private static final Logger logger = LoggerFactory.getLogger(PaymentService.class);
    private static final DateTimeFormatter PAYMENT_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final PaymentPlanRepository paymentPlanRepository;
    private final ContractRepository contractRepository;

    @Autowired
    public PaymentService(PaymentPlanRepository paymentPlanRepository,
                          ContractRepository contractRepository) {
        this.paymentPlanRepository = paymentPlanRepository;
        this.contractRepository = contractRepository;
    }

    /**
     * 处理支付宝异步通知
     */
    @Transactional(rollbackFor = Exception.class)
    public String handleAlipayNotify(Map<String, String> params) {
        try {
            // 1. 验证签名
            boolean verifyResult = Factory.Payment.Common().verifyNotify(params);
            if (!verifyResult) {
                logger.warn("支付宝通知签名验证失败，参数: {}", params);
                return "fail";
            }

            // 2. 验证支付状态
            String tradeStatus = params.get("trade_status");
            if (!"TRADE_SUCCESS".equals(tradeStatus) && !"TRADE_FINISHED".equals(tradeStatus)) {
                logger.info("非成功支付状态，交易状态: {}", tradeStatus);
                return "success";
            }

            // 3. 解析必要参数
            String outTradeNo = params.get("out_trade_no");
            String alipayTradeNo = params.get("trade_no");
            String payTimeStr = params.get("gmt_payment");

            // 参数校验
            if (outTradeNo == null || alipayTradeNo == null || payTimeStr == null) {
                logger.error("支付宝通知参数缺失，outTradeNo={}, alipayTradeNo={}, payTimeStr={}",
                        outTradeNo, alipayTradeNo, payTimeStr);
                return "fail";
            }

            // 4. 查询支付计划
            Optional<PaymentPlan> planOptional = paymentPlanRepository.findByOutTradeNo(outTradeNo);
            if (planOptional.isEmpty()) {
                logger.error("未找到对应付款计划，outTradeNo={}", outTradeNo);
                return "fail";
            }

            PaymentPlan plan = planOptional.get();

            // 5. 防止重复处理
            if (plan.getIsExecuted()) {
                logger.warn("付款计划已支付，无需重复处理，outTradeNo={}", outTradeNo);
                return "success";
            }

            // 6. 更新支付状态（使用Repository的updatePaymentSuccess方法）
            LocalDateTime payTime = LocalDateTime.parse(payTimeStr, PAYMENT_TIME_FORMAT);
            int rowsAffected = paymentPlanRepository.updatePaymentSuccess(
                    outTradeNo,
                    alipayTradeNo,
                    payTime
            );

            if (rowsAffected == 0) {
                logger.error("更新支付状态失败，未影响任何记录，outTradeNo={}", outTradeNo);
                return "fail";
            }

            // 7. **移除了更新合同状态的调用**
            // updateContractStatus(plan.getContract().getId());

            logger.info("支付宝支付通知处理成功，outTradeNo={}, alipayTradeNo={}", outTradeNo, alipayTradeNo);
            return "success";
        } catch (Exception e) {
            logger.error("处理支付宝通知失败，参数: {}", params, e);
            return "fail";
        }
    }

    /**
     * 保留原方法，但不做任何操作（空实现）
     */
    private void updateContractStatus(Long contractId) {
        // 空实现，不更新合同状态
        logger.info("支付结果不影响合同状态，已跳过更新，contractId={}", contractId);
    }
}